package com.net.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;

/**
 * @author  on 2015/6/21.
 * URLEncoding的类
 */
public class UrlEncodeUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlEncodeUtil.class);

    public static String decode(String str, String encoding) {
        if (Strings.isNullOrEmpty(str)) {
            return str;
        }
        try {
            return URLDecoder.decode(str, encoding);
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("decode string failed |str=" + str + " | encoding=" + encoding, e);
            throw new RuntimeException("decode error|str=" + str + " | encoding=" + encoding);
        }
    }

    public static String encode(String str, String encoding) {
        if (Strings.isNullOrEmpty(str)) {
            return str;
        }
        try {
            return URLEncoder.encode(str, encoding);
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("encode string failed|str=" + str + " | encoding=" + encoding, e);
            throw new RuntimeException("encode error|str=" + str + " | encoding=" + encoding);
        }
    }
}
